import axios from 'axios'
import qs from 'qs'
import router from '../router/index'
axios.defaults.timeout = 60000;
axios.defaults.baseURL = 'http://114.116.114.219:8080/';
axios.interceptors.request.use(function (config) {
    return config;
}, function (error) {
    Message.error({
        message: '加载超时'
    });
    return Promise.reject(error);
});

// 添加请求拦截器
axios.interceptors.request.use(
    config => {
        if(localStorage.getItem('adminTokens')){
            config.headers["Authorization-Czinfo"] = `${localStorage.getItem('adminTokens')}`
        }
        return config
    },
    err => {
        return Promise.reject(err)
    }
)
// 添加响应拦截器
axios.interceptors.response.use(
    response => {
        if(response.data.code == 101){
            router.replace({ //跳转到登录页面
                path: '/',
            });
        }
        return response;
    },
    error => { //默认除了2XX之外的都是错误的，就会走这里
    //   if(error.response){
    //     switch(error.response.code){
    //       case 101:
    //         router.replace({ //跳转到登录页面
    //           path: '/login',
    //           query: { redirect: router.currentRoute.fullPath } // 将跳转的路由path作为参数，登录成功后跳转到该路由
    //         });
    //     }
    //   }
    //   return Promise.reject(error.response);
    }
  );
export default {
    post(url,data) {
        return new Promise((resolve,reject) => {
            axios.post(url,data).then(resp => {
                resolve(resp.data)
            }).catch(err =>{
                reject(err)
            })
        })
    },

    get(url, data) {
        return new Promise((resolve,reject) => {
            axios.get(url,data).then(resp => {
                resolve(resp.data)
            }).catch(err =>{
                reject(err)
            })
        })
    },
    put(url, data) {
        return new Promise((resolve,reject) => {
            axios.put(url,qs.stringify(data)).then(resp => {
                resolve(resp.data)
            }).catch(err =>{
                reject(err)
            })
        })
    },
    delete(url, data) {
        return new Promise((resolve,reject) => {
            axios.delete(url,data).then(resp => {
                resolve(resp.data)
            }).catch(err =>{
                reject(err)
            })
        })
    },
    patch(url,data){
        return new Promise((resolve,reject) => {
            axios.patch(url,data).then(resp => {
                resolve(resp.data)
            }).catch(err =>{
                reject(err)
            })
        })
    }
}
